package com.winit.uCloud.manager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.util.Constants;
import com.winit.common.util.FileUtil;
import com.winit.common.util.JSONFileUtil;
import com.winit.common.util.ObjectToString;
import com.winit.core.configuration.util.ConfigRepositoryUtil;
import com.winit.deploy.bean.DeployEnum;
import com.winit.deploy.service.DeployService;
import com.winit.project.core.bean.EditionInfo;
import com.winit.project.core.bean.PackageTypeEnum;
import com.winit.project.core.bean.ProjectInfo;
import com.winit.project.core.branch.Project;
import com.winit.project.core.set.ProjectSetConfig;
import com.winit.project.service.ProjectService;
import com.winit.project.util.ProjectUtil;
import com.winit.uCloud.bean.UCloudInfo;
import com.winit.uCloud.util.UCloudUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by wangjian on 16/10/28.
 */
@Component
public class UCloudManager {

    private static Logger logger = LoggerFactory.getLogger(UCloudManager.class);

    @Autowired
    private ProjectService projectService;

    @Autowired
    private DeployService deployService;

    /**
     * 获取uCloud列表
     * @return
     */
    public List<UCloudInfo> getUCloudList(){
        List<UCloudInfo> list = new ArrayList<>();
        File file = new File(UCloudUtil.UCLOUD_DIR);
        if(!file.exists()){
            return list;
        }
        for (File f:file.listFiles()){
            if(!f.getName().endsWith(".json")){
              continue;
            }

            UCloudInfo info = JSONFileUtil.getFileJsonForBean(f.getAbsolutePath(),UCloudInfo.class);
            if (info == null)
                continue;

            list.add(info);
        }

        Collections.sort(list, new Comparator<UCloudInfo>() {
            @Override
            public int compare(UCloudInfo o1, UCloudInfo o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        return list;
    }

    /**
     * 保存ucloud信息
     * @param info
     * @return
     */
    public boolean saveUCloudInfo(UCloudInfo info){
        logger.info("com.winit.uCloud.manager.UCloudManager.saveUCloudInfo "+ ObjectToString.getString(info));
        return JSONFileUtil.saveFileJson(UCloudUtil.UCLOUD_DIR+info.getName()+".json",info);
    }

    /**
     * 获取ucloud信息
     * @param name
     * @return
     */
    public UCloudInfo getUCloudInfo(String name){
        File file = new File(UCloudUtil.UCLOUD_DIR+name+".json");
        if (!file.exists())
            return null;

        UCloudInfo info = JSONFileUtil.getFileJsonForBean(file.getAbsolutePath(),UCloudInfo.class);
        return info;
    }

    public List<JSONObject> getUCloudProjectInfo(JSONArray array){
        List<JSONObject> list = new ArrayList<>();
        for (int i=0;i<array.size();i++){
            JSONObject object = (JSONObject) array.get(i);
            String name = object.getString("name");
            String version = object.getString("version");
            if(!StringUtils.isEmpty(version)){
                version = version.replaceAll(".version","");
            }else {
                version = "-1";
            }
            String type = object.getString("type");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("trunkName",name);
            if("adempiere".equals(type)){//erp工程
                //分支列表
                List<String> folders = Constants.adFolderMap().get(name);
                List<ProjectInfo> projectInfos = new ArrayList<>();
                for (String s:folders){
                    ProjectInfo info = new ProjectInfo();
                    info.setProjectName(s);
                    projectInfos.add(info);
                }
                jsonObject.put("projectList", projectInfos);
                //选中工程信息
                ProjectInfo projectInfo = null;
                for(ProjectInfo info:projectInfos){
                    File f = new File(info.getProjectName()+"/"+version);
                    if(f.exists()){
                        projectInfo = info;
                        break;
                    }
                }
                if(projectInfo == null){
                    projectInfo = projectInfos.get(0);
                    projectInfo.setProExist(false);
                }
                jsonObject.put("projectInfo",projectInfo);
                //选中的版本
                EditionInfo editionInfo = null;
                if(projectInfo.isProExist()){
                    //版本列表
                    List<EditionInfo> editionInfos = getAdVersion(projectInfo.getProjectName());
                    jsonObject.put("editionList",editionInfos);
                    for (EditionInfo info:editionInfos){
                        if(info.getEditionNum().equals(version)){
                            editionInfo = info;
                            break;
                        }
                    }
                    if(editionInfo == null){
                        editionInfo = new EditionInfo();
                        editionInfo.setEditionNum(version);
                        editionInfo.setShowNum(version);
                        editionInfo.setEditionExist(false);
                    }
                }else {
                    editionInfo = new EditionInfo();
                    editionInfo.setEditionNum(version);
                    editionInfo.setShowNum(version);
                    editionInfo.setEditionExist(false);
                }
                jsonObject.put("editionInfo",editionInfo);
                //online环境版本
                jsonObject.put("onlineVersion","");
                jsonObject.put("qaTestVersion","");
            }else{
                try {
                    if(!projectService.isProjectExist(name)){
                        continue;
                    }
                    //分支列表
                    List<ProjectInfo> projectInfos = projectService.getProjectList(name,PackageTypeEnum.ALL,true,true);
                    jsonObject.put("projectList",projectInfos);
                    ProjectInfo projectInfo = null;
                    //选中的版本
                    EditionInfo editionInfo = null;
                    if(!"-1".equals(version)
                            && !"1".equals(version)
                            && !"default".equals(version)
                            && version.contains("@")) {
                        String projectName = version.split("@")[0];
                        String editionNum = version.split("@")[1];
                        try {
                            //选中工程信息
                            projectInfo = projectService.getProjectInfo(projectName);
                            //版本列表
                            List<EditionInfo> editionInfos = projectService.getProjectEditionList(projectInfo.getProjectName(),true,true);
                            jsonObject.put("editionList",editionInfos);
                            for (EditionInfo info:editionInfos){
                                if(info.getEditionNum().equals(editionNum)){
                                    editionInfo = info;
                                    break;
                                }
                            }
                        }catch (Exception e){
                        }finally {
                            if(projectInfo == null){
                                projectInfo = new ProjectInfo();
                                projectInfo.setProjectName(projectName);
                                projectInfo.setProExist(false);
                            }
                            if(editionInfo == null){
                                editionInfo = new EditionInfo();
                                if("default".equals(editionNum)){
                                    editionInfo.setShowNum("临时版本");
                                }else {
                                    editionInfo.setShowNum(editionNum);
                                }
                                editionInfo.setEditionExist(false);
                                editionInfo.setEditionNum(editionNum);
                            }
                        }
                    }
                    jsonObject.put("projectInfo",projectInfo);
                    jsonObject.put("editionInfo",editionInfo);
                    //online环境版本
                    String onlineVersion = deployService.getOnlineOrStagingVersion(name, DeployEnum.ONLINE,"");
                    jsonObject.put("onlineVersion",onlineVersion);
                    //测试通过版本
                    String qaTestVersion = deployService.getOnlineOrStagingVersion(name, DeployEnum.TESTPASS,"");
                    jsonObject.put("qaTestVersion",qaTestVersion);
                } catch (Exception e) {
                    logger.error("com.winit.uCloud.manager.UCloudManager.getUCloudProjectInfo 异常",e);
                    continue;
                }
            }

            list.add(jsonObject);
        }
        return list;
    }

    public List<EditionInfo> getAdVersion(String folderPath){
        List<EditionInfo> list = new ArrayList<>();
        List<File> l = FileUtil.getFileByLevel(new File(folderPath),1);
        if(l.size() != 0){
            l = FileUtil.sortFileDESC(l);
            for (File file:l.subList(0,l.size()>=Constants.VM_PHP_AD_LIST_COUNT?Constants.VM_PHP_AD_LIST_COUNT:l.size())){
                EditionInfo info = new EditionInfo();
                info.setEditionNum(file.getName());
                info.setShowNum(file.getName());
                list.add(info);
            }
        }
        return list;
    }

    public boolean checkConfig(String projectName,String envName) throws Exception {
        Project project = new Project(projectName,true);
        ProjectSetConfig setConfig = project.getProjectSetConfig();

        String baseConfigPath = project.getProjectCode().getCodePath();
        String subModule = setConfig.getSubModule();

        if(!StringUtils.isEmpty(subModule)){
            baseConfigPath = baseConfigPath + "/" + subModule;
        }
        return ProjectUtil.checkConfigFile(ConfigRepositoryUtil.getConfigEnvPath(Constants.CONFIG_REPOSITORY_PATH,envName)+"/"+setConfig.getConfigProjectName(),baseConfigPath);
    }
}
